/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.gui.config;

import nfse.gui.client.NetFSEClient;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.*;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;  
import com.gwtext.client.widgets.MessageBox;  
import com.gwtext.client.widgets.Window;  
import com.gwtext.client.widgets.event.ButtonListenerAdapter;  

public class NetFlowConfigDialogBox extends Window {

    final ListBox sensorsComboBox = new ListBox();

    final TextBox portTextBox = new TextBox();

    boolean cancelled = false;

    boolean isNew = false;
    
    SensorConfigTable configTable = null;

    public NetFlowConfigDialogBox(SensorConfigTable configs) {
        final NetFlowConfigDialogBox note = this;
        this.configTable = configs;
        
        this.setShadow(true);
        this.setFrame(true);
        this.setModal(true);
        this.setIconCls("pac-icon");
        
        FlexTable table = new FlexTable();

        int idx = -1;

        table.setHTML(++idx, 0, "<b>Sensor</b>");
        table.setWidget(++idx, 0, sensorsComboBox);
        table.setHTML(++idx, 0, "<b>Listen on Port</b>");
        table.setWidget(++idx, 0, portTextBox);

        Button cancelButton = new Button();
        cancelButton.setText("Cancel");
        cancelButton.addListener(new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject obj) {
                cancelled = true;
                note.hide();

            }
        });

        Button okButton = new Button();
        okButton.setText("OK");
        okButton.addListener(new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject obj) {

                try {
                    int val = Integer.parseInt(portTextBox.getText().trim());
                } catch (Exception e) {
                    MessageBox.alert("The value entered in the 'Listen on Port' text box must be a valid UDP port.");
                    return;
                }
                
                NetFlowConfig netflowConfig = getNetFlowConfig();
                if (isNew()) {
                    addNetFlowConfig(netflowConfig);
                } else {
                    editNetFlowConfig(netflowConfig);
                }
                
                cancelled = false;
                note.hide();

            }
        });

        Button resetButton = new Button();
        resetButton.setText("Reset");
        resetButton.addListener(new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject obj) {
                reset();
            }
        });

        this.addButton(resetButton);
        this.addButton(okButton);
        this.addButton(cancelButton);

        this.add(table);
    }

    public NetFlowConfig getNetFlowConfig() {
        NetFlowConfig cse = new NetFlowConfig();
        cse.sensor = Integer.parseInt(sensorsComboBox.getValue(sensorsComboBox.getSelectedIndex()));
        cse.port = Integer.parseInt(portTextBox.getText().trim());
        return cse;
    }

    public void set(NetFlowConfig sc) {
        for (int i = 0; i < sensorsComboBox.getItemCount(); i++) {
            int sensor = Integer.parseInt(sensorsComboBox.getValue(i));
            if (sensor == sc.sensor) {
                sensorsComboBox.setSelectedIndex(i);
                break;
            }
        }
        portTextBox.setText(sc.port + "");
    }

    public boolean isCancelled() {
        return cancelled;
    }

    public void setSensors(SensorInfo[] sensors) {
        sensorsComboBox.clear();
        for (int i = 0; i < sensors.length; i++)
            sensorsComboBox.addItem(sensors[i].sensorName, sensors[i].id + "");
    }

    public boolean isNew() {
        return isNew;
    }

    public void setNew(boolean isNew) {
        this.isNew = isNew;
        if (isNew) {
            sensorsComboBox.setEnabled(true);
            reset();
        } else {
            sensorsComboBox.setEnabled(false);
        }
    }

    private void reset() {
        portTextBox.setText("");
        sensorsComboBox.setSelectedIndex(0);
    }
    
    private void addNetFlowConfig(NetFlowConfig config) {
        ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirect("NetFSEClient.html");
            }

            public void onSuccess(Object result) {
                NetFSEClient.showGenericDialog("NetFlow Configuration Change", (String) result);
                configTable.netflowConfigs();
            }
        };

        nfseService.addNetFlowConfig(config, callback);
    }
    
    private void editNetFlowConfig(NetFlowConfig config) {
        ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirect("NetFSEClient.html");
            }

            public void onSuccess(Object result) {
                NetFSEClient.showGenericDialog("NetFlow Configuration Change", (String) result);
                configTable.netflowConfigs();
            }
        };

        nfseService.editNetFlowConfig(config, callback);
    }
}
